package org.example.onlinejudge.model;

import jakarta.persistence.*;
import java.util.HashSet;
import java.util.Set;

/**
 * 角色实体类
 * 负责表示系统中的角色信息
 * 实现逻辑：
 * 1. 使用JPA注解映射到数据库中的role表
 * 2. 包含角色基本信息：ID、角色代码和角色名称
 * 3. 角色代码定义：0-管理员, 1-老师, 2-学生
 * 4. 通过@ManyToMany建立与Permission实体的多对多关系，使用FetchType.EAGER立即加载权限
 * 5. 通过@ManyToMany(mappedBy = "roles")建立与User实体的多对多关系
 * 6. 提供添加和删除权限的便捷方法
 */
@Entity
@Table(name = "role")
public class Role {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "role_code", length = 2)
    private String roleCode; // 0-管理员, 1-老师, 2-学生

    @Column(name = "role_name", length = 50)
    private String roleName;

    // 多对多关系：角色-权限
    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(
        name = "sys_role_perm",
        joinColumns = @JoinColumn(name = "role_id"),
        inverseJoinColumns = @JoinColumn(name = "perm_id")
    )
    private Set<Permission> permissions = new HashSet<>();

    // 多对多关系：角色-用户（反向）
    @ManyToMany(mappedBy = "roles")
    private Set<User> users = new HashSet<>();

    // Getters and Setters
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getRoleCode() {
        return roleCode;
    }

    public void setRoleCode(String roleCode) {
        this.roleCode = roleCode;
    }

    public String getRoleName() {
        return roleName;
    }

    public void setRoleName(String roleName) {
        this.roleName = roleName;
    }

    public Set<Permission> getPermissions() {
        return permissions;
    }

    public void setPermissions(Set<Permission> permissions) {
        this.permissions = permissions;
    }

    public Set<User> getUsers() {
        return users;
    }

    public void setUsers(Set<User> users) {
        this.users = users;
    }

    public void addPermission(Permission permission) {
        this.permissions.add(permission);
    }

    public void removePermission(Permission permission) {
        this.permissions.remove(permission);
    }
}


